package sz.szsmk.citizencard.ui.activity;

import android.annotation.SuppressLint;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.chenenyu.router.annotation.Route;
import com.google.gson.Gson;

import org.json.JSONArray;

import java.util.ArrayList;
import java.util.List;

import sz.szsmk.citizencard.DaggerApplication;
import sz.szsmk.citizencard.R;
import sz.szsmk.citizencard.databinding.AddressAddActivityBinding;
import sz.szsmk.citizencard.dialog.SuccessDialog;
import sz.szsmk.citizencard.ioc.Compontent.DaggerCommonActivityComponent;
import sz.szsmk.citizencard.model.network.bean.CityBean;
import sz.szsmk.citizencard.model.network.bean.GetJsonDataUtil;
import sz.szsmk.citizencard.model.network.bean.JsonBean;
import sz.szsmk.citizencard.model.network.bean.response.IbaseBean;
import sz.szsmk.citizencard.model.network.bean.response.UserBean;
import sz.szsmk.citizencard.mvp.contract.AdressAddContact;
import sz.szsmk.citizencard.mvp.presenter.AdressAddPresenter;
import sz.szsmk.citizencard.ui.base.IBaseActivity;
import sz.szsmk.citizencard.util.PubUtils;
import sz.szsmk.citizencard.util.zxyh.CheckContentUtil;

/**
 * Copyright (c)2018
 * author: zdh
 * created on: 2018/7/11 8:52
 * description:
 */
@Route("adressadd")
public class AdressAddActivity extends IBaseActivity<AdressAddPresenter, AddressAddActivityBinding>
        implements AdressAddContact.IAdressAddView, View.OnClickListener, TextWatcher {

    //    private ArrayList<String> cityList;
    private List<CityBean.ProvincesBean> data;
    private int selectIndex;
    private TextView addCity;
    private int mDefault ;
    private int addressId;
    private String key;

    //    private ArrayList<JsonBean> options1Items = new ArrayList<>();
    private ArrayList<ArrayList<String>> options2Items = new ArrayList<>();
    private ArrayList<ArrayList<ArrayList<String>>> options3Items = new ArrayList<>();
    private Thread thread;
    private static final int MSG_LOAD_DATA = 0x0001;
    private static final int MSG_LOAD_SUCCESS = 0x0002;
    private static final int MSG_LOAD_FAILED = 0x0003;

    private String city;
    private SuccessDialog dialog;
    private String des;

    private ArrayList<JsonBean> options1Items = new ArrayList<>();


    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_LOAD_DATA:
                    if (thread == null) {//如果已创建就不再重新创建子线程了

                        Toast.makeText(AdressAddActivity.this, "Begin Parse Data", Toast.LENGTH_SHORT).show();
                        thread = new Thread(new Runnable() {
                            @Override
                            public void run() {
                                // 子线程中解析省市区数据
                                initJsonData();
                            }
                        });
                        thread.start();
                    }
                    break;

                case MSG_LOAD_SUCCESS:
                    Toast.makeText(AdressAddActivity.this, "Parse Succeed", Toast.LENGTH_SHORT).show();
//                    isLoaded = true;
                    break;

                case MSG_LOAD_FAILED:
                    Toast.makeText(AdressAddActivity.this, "Parse Failed", Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };

    @Override
    protected int attachLayoutRes() {
        return R.layout.address_add_activity;
    }

    @Override
    protected void initInjector() {
        DaggerCommonActivityComponent.builder().appCompontent(DaggerApplication.getAppComponent())
                .build().inject(this);

    }

    @Override
    protected void initViews() {
        key = getIntent().getStringExtra("key");
        initJsonData();

        if (key.equals("add")) {
            dataBinding.titleLayout.settingTitle.setText("新增地址");
        } else {
            dataBinding.titleLayout.settingTitle.setText("编辑地址");
            String name = getIntent().getStringExtra("name");
            String address = getIntent().getStringExtra("address");
            String mobile = getIntent().getStringExtra("mobile");
            String location = getIntent().getStringExtra("location");
            String isDefault = getIntent().getStringExtra("isDefault");
            String contact = getIntent().getStringExtra("contact");
            if (isDefault.equals("1")) {
                dataBinding.addBox.setChecked(true);
                mDefault= 1;
            } else {
                dataBinding.addBox.setChecked(false);
                mDefault= 0;
            }
//            String substring = address.substring(location.length(), address.length());
            addressId = getIntent().getIntExtra("addressId", 0);
//            if (location.length() > 0 && address.length() > 0) {
//                des = address.substring(location.length(), address.length());
//            }
            dataBinding.addDesAddress.setText(address);
            dataBinding.addPhone.setText(mobile);
            dataBinding.addName.setText(name);
            dataBinding.addCity.setText(location);
        }
        dataBinding.titleLayout.back.setOnClickListener(this);
        dataBinding.adressAddChange.setOnClickListener(this);
        dataBinding.addAddressSure.setOnClickListener(this);
        addCity = dataBinding.addCity;
//        setPick();
        dataBinding.addBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    mDefault = 1;
                } else {
                    mDefault = 0;
                }
            }
        });
//        getAdress();

        dataBinding.addName.addTextChangedListener(this);
        dataBinding.addPhone.addTextChangedListener(this);
        dataBinding.addDesAddress.addTextChangedListener(this);



    }


    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void updateViews() {

    }

    @Override
    public void addSuccess() {
        dialog = new SuccessDialog(this, "操作成功");

        dialog.show();
        new Thread() {
            @Override
            public void run() {
                super.run();
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                dialog.cancel();
                dialog.dismiss();
                finish();
            }
        }.start();
    }

    @Override
    public void addFalie(UserBean loginResponse) {

    }

    @Override
    public void updataSuccess() {
        final SuccessDialog dialog = new SuccessDialog(this, "修改成功");
        dialog.setOnOkClickListener(new SuccessDialog.OnOkClickListener() {
            @Override
            public void onOkClick() {
                finish();
            }
        });
        dialog.show();
        new Thread() {
            @Override
            public void run() {
                super.run();
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                dialog.cancel();
                finish();
            }
        }.start();
    }

    @Override
    public void updataFaile(IbaseBean response) {
        PubUtils.popTipOrWarn(this, response.getMessage());
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.back) {
            finish();
        } else if (id == R.id.adress_add_change) {
            showPickerView();
//                pvOptions.show();
//                setCity();
        } else if (id == R.id.add_address_sure) {
            String name = dataBinding.addName.getText().toString();
            String phone = dataBinding.addPhone.getText().toString();
//                String city = dataBinding.addCity.getText().toString();
            String desAddress = dataBinding.addDesAddress.getText().toString();

            city = dataBinding.addCity.getText().toString().trim();
            String replace = city.replace(" ", "-");
            String mAdress = desAddress;

            if (TextUtils.isEmpty(name)) {
                PubUtils.popTipOrWarn(this, "收货人不能为空");
                return;
            }
            if (TextUtils.isEmpty(phone)) {
                PubUtils.popTipOrWarn(this, "手机号不能为空");
                return;
            }
            if (TextUtils.isEmpty(city)) {
                PubUtils.popTipOrWarn(this, "请选择省市区");
                return;
            }

            if (TextUtils.isEmpty(desAddress)) {
                PubUtils.popTipOrWarn(this, "请输入详细地址");
                return;
            }
            if (key.equals("add")) {
                mPresenter.addAdress(name, phone, mAdress, mDefault, replace);
            } else {
                mPresenter.updataAdress(name, phone, mAdress, mDefault, addressId, replace);
            }
        }
    }


    private void showPickerView() {// 弹出选择器

        OptionsPickerView pvOptions = new OptionsPickerBuilder(AdressAddActivity.this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                String tx = options1Items.get(options1).getPickerViewText() + "-"
                        + options2Items.get(options1).get(option2) + "-"
                        + options3Items.get(options1).get(option2).get(options3);
                dataBinding.addCity.setText(tx);
                CheckContentUtil.checkPhoneListContent(AdressAddActivity.this,dataBinding.addAddressSure,dataBinding.addCity,dataBinding.addPhone,dataBinding.addName,dataBinding.addDesAddress);
            }
        }).isDialog(true)
                .build();
        pvOptions.setPicker(options1Items, options2Items, options3Items);
        pvOptions.show();

//        OptionsPickerBuilder  pvOptions = new  OptionsPickerBuilder(this, new OnOptionsSelectListener() {
//            @Override
//            public void onOptionsSelect(int options1, int options2, int options3, View v) {
//
//            }
//        }.setOptionsSelectChangeListener(new OnOptionsSelectChangeListener() {
//            @Override
//            public void onOptionsSelectChanged(int options1, int options2, int options3) {
//                String str = "options1: " + options1 + "\noptions2: " + options2 + "\noptions3: " + options3;
////                Toast.makeText(MainActivity.this, str, Toast.LENGTH_SHORT).show();
//            }
//        })
//                .setSubmitText("确定")//确定按钮文字
//                .setCancelText("取消")//取消按钮文字
//                .setTitleText("城市选择")//标题
//                .setSubCalSize(18)//确定和取消文字大小
//                .setTitleSize(20)//标题文字大小
//                .setTitleColor(Color.BLACK)//标题文字颜色
//                .setSubmitColor(Color.BLUE)//确定按钮文字颜色
//                .setCancelColor(Color.BLUE)//取消按钮文字颜色
//                .setTitleBgColor(0xFF333333)//标题背景颜色 Night mode
//                .setBgColor(0xFF000000)//滚轮背景颜色 Night mode
//                .setContentTextSize(18)//滚轮文字大小
//                .setLinkage(false)//设置是否联动，默认true
//                .setLabels("省", "市", "区")//设置选择的三级单位
//                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
//                .setCyclic(false, false, false)//循环与否
//                .setSelectOptions(1, 1, 1)  //设置默认选中项
//                .setOutSideCancelable(false)//点击外部dismiss default true
//                .isDialog(true)//是否显示为对话框样式
//                .isRestoreItem(true)//切换时是否还原，设置默认选中第一项。
//                .build();
//
//        pvOptions.setPicker(options1Items, options2Items, options3Items);//添加数据源
    }

    private void initJsonData() {//解析数据

        /**
         * 注意：assets 目录下的Json文件仅供参考，实际使用可自行替换文件
         * 关键逻辑在于循环体
         *
         * */
        String JsonData = new GetJsonDataUtil().getJson(this, "province.json");//获取assets目录下的json文件数据

        ArrayList<JsonBean> jsonBean = parseData(JsonData);//用Gson 转成实体

        /**
         * 添加省份数据
         *
         * 注意：如果是添加的JavaBean实体，则实体类需要实现 IPickerViewData 接口，
         * PickerView会通过getPickerViewText方法获取字符串显示出来。
         */
        options1Items = jsonBean;

        for (int i = 0; i < jsonBean.size(); i++) {//遍历省份
            ArrayList<String> CityList = new ArrayList<>();//该省的城市列表（第二级）
            ArrayList<ArrayList<String>> Province_AreaList = new ArrayList<>();//该省的所有地区列表（第三极）

            for (int c = 0; c < jsonBean.get(i).getCityList().size(); c++) {//遍历该省份的所有城市
                String CityName = jsonBean.get(i).getCityList().get(c).getName();
                CityList.add(CityName);//添加城市
                ArrayList<String> City_AreaList = new ArrayList<>();//该城市的所有地区列表

                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (jsonBean.get(i).getCityList().get(c).getArea() == null
                        || jsonBean.get(i).getCityList().get(c).getArea().size() == 0) {
                    City_AreaList.add("");
                } else {
                    City_AreaList.addAll(jsonBean.get(i).getCityList().get(c).getArea());
                }
                Province_AreaList.add(City_AreaList);//添加该省所有地区数据
            }

            /**
             * 添加城市数据
             */
            options2Items.add(CityList);

            /**
             * 添加地区数据
             */
            options3Items.add(Province_AreaList);
        }

//        mHandler.sendEmptyMessage(MSG_LOAD_SUCCESS);

    }


    public ArrayList<JsonBean> parseData(String result) {//Gson 解析
        ArrayList<JsonBean> detail = new ArrayList<>();
        try {
            JSONArray data = new JSONArray(result);
            Gson gson = new Gson();
            for (int i = 0; i < data.length(); i++) {
                JsonBean entity = gson.fromJson(data.optJSONObject(i).toString(), JsonBean.class);
                detail.add(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
            mHandler.sendEmptyMessage(MSG_LOAD_FAILED);
        }
        return detail;
    }

    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void afterTextChanged(Editable editable) {
        CheckContentUtil.checkPhoneListContent(AdressAddActivity.this,dataBinding.addAddressSure,dataBinding.addCity,dataBinding.addPhone,dataBinding.addName,dataBinding.addDesAddress);
    }
}
